/**
 * @ Author: luoqi
 * @ Create Time: 2024-03-03 00:02
 * @ Modified by: luoqi
 * @ Modified time: 2024-03-08 23:57
 * @ Description:
 */

#include <rtdevice.h>
#include <rtthread.h>
#include <stdbool.h>
#include <stdint.h>

#define DBG_LVL DBG_INFO
#define DBG_TAG "BLINK"
#include <rtdbg.h>

#include "blink.h"
#include "../common.h"

static rt_base_t pin_blink;

static int frq = 1000;

static void _blink_hdl(void *args);

int blink_init()
{
    pin_blink = rt_pin_get("PC.13");
    rt_pin_mode(pin_blink, PIN_MODE_OUTPUT);
    rt_pin_write(pin_blink, PIN_HIGH);
    frq = 1000;
    rt_thread_t task = rt_thread_create("blink", _blink_hdl, RT_NULL, 256, 3, 1);
    if(task != RT_NULL){
        rt_thread_startup(task);
        LOG_I("blink thread startup");
    }else{
        LOG_E("blink task create error");
    }

    return 0;
}

void _blink_hdl(void *args)
{
    static bool state = false;

    while (1) {
        if(state){
            rt_pin_write(pin_blink, PIN_LOW);
        }else{
            rt_pin_write(pin_blink, PIN_HIGH);
        }
        state = !state;
        rt_thread_mdelay(frq);
    }
}

static int _cmd_blink(int argc, char **argv)
{
    if(argc == 1){
        MSG(" frq: %d\r\n", frq);
    } else if(argc == 2){
        frq = atoi(argv[1]);
    }else{
        ARG_ERR("blink");
    }
    return 0;
}
MSH_CMD_EXPORT_ALIAS(_cmd_blink, blink, blink frq set command);
